from PySide2 import QtWidgets
from PySide2.QtGui import QIcon

from robotController import share
from robotController.elementUI.window_element import template_move_window
from robotController.util import fileSelect
from PySide2.QtWidgets import QPushButton, QHBoxLayout, QWidget, QMessageBox, QTableWidgetItem, QAbstractItemView

import json
import requests

from robotController.util.TableWidgetUtil import TableWidgetUtil
from robotController.util.requestUtil import requestUtil

class bind:
    def __init__(self):
        self.ui = share.SI.main.ui

    def incident(self):
        # 绑定上传按钮事件
        self.ui.template_submit_button.clicked.connect(lambda: self.submit_file())
        self.ui.template_submit_button.setIcon(QIcon("./static/img/提交.png"))
        # 绑定查询按钮
        self.ui.template_select_button.clicked.connect(lambda : self.findAll())
        self.ui.template_select_button.setIcon(QIcon("./static/img/查询.png"))
        # 绑定模板查看界面返回按钮
        self.ui.template_check_back_button.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(3))

    def findAll(self):
        # 查询分组及单位
        from robotController.binding.home_bind import home_bind
        ug = home_bind().get_ug_comboBox_fun()
        name = self.ui.template_select_lineEdit.text() if self.ui.template_select_lineEdit.text() != "" else "None"
        # 拉取模板数据头列表
        dataMap = requestUtil("/template/findByGroup/" + ug["group_value"] + "/" + ug["unit_value"] + "/" + name,"GET").dataMap

        for index,item in enumerate(dataMap["data"]):
            item["buttons"] = self.buttonForRow(item["id"],item["name"])

        dataList = dataMap['data']
        # 准备表头数据
        head_list = [{'key':"目标表名","value":"name"},{'key':"分组名称","value":"gname"},{'key':"单位名称","value":"uname"},{'key':"操作","value":"buttons"}]
        TableWidgetUtil().render(self.ui.template_tableWidget,dataList,head_list)
        TableWidgetUtil().head_color_show(self.ui.template_tableWidget)

    # 列表内添加按钮
    def buttonForRow(self, id,name):
        widget = QWidget()

        # 查看
        alterBtn = QPushButton('查看')
        alterBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:#192D9E;
                                    }
                                     
                                    QPushButton:hover{
                                    	color: #192D9E;
                                    	text-decoration:underline;
                                    }''')

        # 上移
        moveUpBtn = QPushButton('位置')
        moveUpBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:#192D9E;
                                    }
                                     
                                    QPushButton:hover{
                                    	color: #192D9E;
                                    	text-decoration:underline;
                                    }''')

        # 删除
        deleteBtn = QPushButton('删除')
        deleteBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:50px;
                                    border-style: outset;
                                    color:red;}
                                     
                                    QPushButton:hover{
                                    	color: red;
                                    	text-decoration:underline;
                                    }''')

        alterBtn.clicked.connect(lambda: self.alter_fun(str(id),name))
        moveUpBtn.clicked.connect(lambda: self.move_up_fun(str(id)))
        deleteBtn.clicked.connect(lambda: self.del_fun(str(id)))

        hLayout = QHBoxLayout()
        hLayout.addWidget(alterBtn)
        hLayout.addWidget(moveUpBtn)
        hLayout.addWidget(deleteBtn)
        hLayout.setContentsMargins(5, 2, 5, 2)
        widget.setLayout(hLayout)
        return widget

    # 删除对应
    def del_fun(self, id):

        A = QMessageBox.question(self.ui.template_tableWidget, '确认', '是否删除该模板?', QMessageBox.Yes | QMessageBox.No)

        if A == QMessageBox.No:
            return

        url = share.RURL.backendUrl + "/template/delete/" + id
        requests.encoding = 'utf-8'
        result = requests.request(method="DELETE", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)
        try:
            if dataMap["flag"] == True:
                QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", dataMap["message"])
                # 查询头元数据列表
                self.findAll()
        except Exception as e:
            print(e)
            QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", "删除失败")

    # 查看模板数据
    def alter_fun(self, id,name):
        # 更改模板页模板名
        self.ui.template_name_lable.setText(name);

        # 根据id查询模板信息
        dataMap = requestUtil("/template/findByPid/" + id,"GET").dataMap
        dataMap = [json.loads(item["data"], strict=False) for index,item in enumerate(dataMap["data"])]

        tableWidget = self.ui.template_check_tableWidget
        # 清空列表
        tableWidget.clearContents()

        #         设置表格行列数
        tableWidget.setRowCount(len(dataMap))
        tableWidget.setColumnCount(len(dataMap[0]))

        # 禁止修改
        tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        for rowIndex,rowItem in enumerate(dataMap):
            for colIndex,colItem in enumerate(rowItem):
                tableWidget.setItem(rowIndex, colIndex, QTableWidgetItem(str(colItem)))

        self.ui.stackedWidget.setCurrentIndex(9)

    # 模板位置改变
    def move_up_fun(self,id):
        template_window = template_move_window(id)
        template_window.show()

    # 提交模板
    def submit_file(self):
        # 选择模板数据位置
        data_address = fileSelect.file_address()
        try:
            file_name = data_address[fileSelect.find_last(data_address, "/"):]
            files = {'file': (file_name, open(data_address, 'rb'))}

            # 查询分组及单位
            from robotController.binding.home_bind import home_bind
            ug = home_bind().get_ug_comboBox_fun()
            url = share.RURL.backendUrl + "/template/templateImport/" + ug["group_value"] + "/" + ug["unit_value"]

            result = requests.request(method="POST", url=url, files=files, verify=False, headers=share.token.headers)
            dataMap = json.loads(result.text)
            if dataMap["flag"]:
                QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", dataMap["message"])
                # 查询头元数据列表
                self.findAll()
        except:
            QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", "提交模板据失败")